// script.js
var backend_url = "http://47.113.194.165:5001";

document.getElementById('send-button').addEventListener('click', async function () {
    var input = document.getElementById('message-input');
    var messages = document.querySelector('.chat-messages');
    var senderMessage = document.createElement('div');
    var receiverMessage = document.createElement('div');


    if (input.value.trim() !== '') {
        senderMessage.classList.add('message', 'sender');
        senderMessage.textContent = input.value;
        messages.appendChild(senderMessage);

        // receiverMessage.classList.add('message', 'receiver');
        // receiverMessage.textContent = "啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"; // replace with actual response
        // messages.appendChild(receiverMessage);


        getReply(input.value).then(reply => {
            createReceiverMessage(receiverMessage, messages, reply);
        });



//         getReply(input.value).then(reply => {
//             receiverMessage.classList.add('message', 'receiver');
//             receiverMessage.textContent = reply; // replace with actual response
//             messages.appendChild(receiverMessage);
//
//             // Create like button
//             var likeButton = document.createElement('button');
//             likeButton.classList.add('like-button');
//             likeButton.textContent = '👍';
//             receiverMessage.appendChild(likeButton);
//
//             // Create dislike button
//             var dislikeButton = document.createElement('button');
//             dislikeButton.classList.add('dislike-button');
//             dislikeButton.textContent = '👎';
//             receiverMessage.appendChild(dislikeButton);
//
//
//
//
//         });
        input.value = '';
        messages.scrollTop = messages.scrollHeight;
    }
});

function getReply(question) {
    return new Promise((resolve, reject) => {
        fetch(backend_url + '/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                text: question,
                bot_name: '陈小云奶奶'
            })
        })
            .then(response => response.json())
            .then(data => {
                console.log(data);
                resolve(data.reply);
            })
            .catch(error => {
                console.error('Error:', error);
                reject(error);
            });
    });
}

function createReceiverMessage(receiverMessage,messages, reply) {
    receiverMessage.classList.add('message', 'receiver');
    receiverMessage.textContent = reply ; // replace with actual response
    messages.appendChild(receiverMessage);

    var br = document.createElement('hr')
    br.classList.add('split')
    receiverMessage.appendChild(br)


    // Create like button
    var likeButton = document.createElement('button');
    likeButton.classList.add('like-button');
    likeButton.onclick = like;
    var likeImage = document.createElement('img');
    likeImage.src = 'like.svg';
    likeButton.appendChild(likeImage);
    // likeButton.textContent = '👍';
    receiverMessage.appendChild(likeButton);

    // Create dislike button
    var dislikeButton = document.createElement('button');
    dislikeButton.classList.add('dislike-button');
    dislikeButton.onclick = openFeedbackModal;
    var unLikeImage = document.createElement('img');
    unLikeImage.src = 'unlike.svg';
    dislikeButton.appendChild(unLikeImage);

    // dislikeButton.textContent = '👎';
    receiverMessage.appendChild(dislikeButton);

}

async function getReply1(question) {
    let reply = "嗯嗯";

    fetch(backend_url + '/chat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            text: question,
            bot_name: '陈小云奶奶'
        })
    })
        .then(response => response.json())
        .then(data => {
                console.log(data);
                reply = data.reply;


            }
        );

    return reply;
}
// 获取模态对话框和关闭按钮
var modal = document.getElementById("myModal");
var btn = document.getElementById("openModal");
var span = document.getElementsByClassName("close")[0];
var feedbackButton = document.getElementById("feedback-button");
var feedbackInput = document.getElementById("feedback-input");
var replyNode;
var questionNode;
var unlikeImgNode;


function openFeedbackModal() {
    openModal();

    unlikeImgNode = this.children[0];
    replyNode = this.parentNode;

    questionNode = this.parentNode.previousElementSibling;
};

// 打开模态对话框的函数
function openModal() {
    modal.style.display = "block";
feedbackInput.focus(); // 让输入框获得焦点

}


// 关闭模态对话框的函数
function closeModal() {
    modal.style.display = "none";
}

// 发送按钮的点击事件
function send() {
    // 这里可以添加发送逻辑，例如通过AJAX发送数据
    showInfoTips("您说的话我牢牢记在心里了！我会一直保持进化的！请继续和我聊天吧！"
        // + feedbackInput.value
    );
    // 确保能获取到同级元素中的sender内容
    if (questionNode && questionNode.classList.contains('sender')) {
        var senderContent = questionNode.textContent;
        sendFeedback(senderContent, replyNode.textContent, feedbackInput.value, "dislike");

        // console.log(senderContent); // 输出sender元素的内容
    }


    unlikeImgNode.src = "unlike-filled.svg";
    feedbackInput.value = ""; // 清空输入框
    closeModal();
}

// 为打开按钮添加点击事件监听器
btn.onclick = function () {
    openModal();

    unlikeImgNode = this.children[0];
    replyNode = this.parentNode;

    questionNode = this.parentNode.previousElementSibling;
};

// 为关闭按钮添加点击事件监听器
span.onclick = closeModal;

// 为发送按钮添加点击事件监听器
feedbackButton.onclick = send;

// 点击模态对话框外部也关闭对话框
window.onclick = function(event) {
    if (event.target === modal) {
        closeModal();
    }
}

function like() {
    //todo 判断是否已经点过赞，若已经点过赞则不需要再发送反馈
    this.children[0].src = "like-filled.svg";
    showInfoTips("谢谢您的点赞！我会牢牢记住这句话的！请继续和我聊天吧！");

    replyNode = this.parentNode;
    questionNode = this.parentNode.previousElementSibling;

    // 确保能获取到同级元素中的sender内容
    if (questionNode && questionNode.classList.contains('sender')) {
        var senderContent = questionNode.textContent;
        sendFeedback(senderContent, replyNode.textContent, "好", "like");

        console.log(senderContent); // 输出sender元素的内容
    }
}

function showInfoTips(infoText) {
    // 获取按钮和提示信息元素
    var infoTipNode = document.getElementById('info-tip');

    infoTipNode.textContent = infoText;
    // 显示提示信息
    infoTipNode.style.display = 'block';

    // 设置定时器，在一秒后隐藏提示信息
    setTimeout(function() {
        infoTipNode.style.display = 'none';
    }, 1000); // 1000毫秒后执行隐藏操作
}

function sendFeedback(question, answer, feedback_content, attitude){
    fetch( backend_url + '/feedback', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: question,
            answer: answer,
            feedback_content: feedback_content,
            attitude: attitude
        })
    })
        .then(response => response.json())
        .then(data => {
                console.log(data);
            }
        );
}